package Fliter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(value = "/*")
public class SessionFliter extends HttpFilter {

    private boolean isStaticResource(String servletPath){
        return servletPath.endsWith(".css")
                || servletPath.endsWith(".js")
                || servletPath.endsWith(".jpg")
                || servletPath.endsWith(".png");
    }
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        String servletPath = req.getServletPath();

        if (isStaticResource(servletPath)) {
            chain.doFilter(req,res);
            return;
        }

        switch (servletPath){
            case "/login.manager":
            case "/logout.manager":
            case "/findNumber.manager":
            case "/login.html":
                chain.doFilter(req,res);
                break;
            default:
                HttpSession session = req.getSession();
                if (session.getAttribute("manager") == null) {
                    res.sendRedirect(req.getContextPath() + "/login.html");
                } else {
                    chain.doFilter(req,res);
                }
                break;
        }
    }
}
